<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <div style="width: 100px;height: 300px;background: linear-gradient(#A5A8BA 50%,white 50%);">

        </div>
        <button onclick="handlePlay()">播放</button>
        <button onclick="handleStop()">暂停</button>
        <script>
            let context = null;
            let musicBufferArray = null;
            let musicBuffer = null;
            let source = null;
            let musicUrl =
                "http://m8.music.126.net/20211224154104/7d4d8c8240c5653b6ce242271e5a83fa/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3625444344/2c17/dfdd/4f2c/65125f352b373baac9146080707c8675.mp3";
            const playMusic = () => {
                source = context.createBufferSource();
                source.buffer = musicBuffer;
                source.connect(context.destination);
                source.start(0);
            };
            //将ArrayBuffer解码成AudioBuffer
            const initMusic = arrayBuffer => {
                context.decodeAudioData(arrayBuffer, buffer => {
                    musicBuffer = buffer;
                    playMusic();
                });
            };
            const fetchArrayBufferedAudio = url => {
                fetch(url).then(async res => {
                    const result = await res.arrayBuffer();
                    musicBufferArray = result;
                    initMusic(musicBufferArray);
                });
            };
            const handlePlay = () => {
                context = new AudioContext();
                const outputTimesStamp = context.getOutputTimestamp();
                setInterval(() => {
                    console.log(outputTimesStamp);
                }, 1000);
                fetchArrayBufferedAudio(musicUrl);
            };
            const handleStop = () => {
                source?.stop(0);
            };
        </script>
    </body>
</html>
